<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods)">
        <my-goods :goods="goods"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        // 请求参数对象
        queryObj: {
          query: '', //楼层参数
          cid: '', //分类参数
          pagenum: 1,
          pagesize: 10
        },
        goodsList: [], //商品列表
        total: 0, //商品总条数
        isLoading: false
      }
    },

    onLoad(options) {
      // 将楼层参数与分类参数转存到 this.queryObj 对象中
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      // 商品列表的请求
      this.getGoodsList()
    },

    methods: {
      // 商品列表的请求
      async getGoodsList(cb) {
        // 请求前打开节流阀
        this.isLoading = true
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        // 请求结束关闭节流阀
        this.isLoading = false
        cb && cb()
        if (res.meta.status !== 200) {
          return uni.$showMsg()
        }
        // 新旧数据拼接
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
        console.log(this.goodsList)
      },

      // 底部上拉加载
      onReachBottom() {
        // 判断页面数据是否加载完毕
        if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('页面加载完毕!')
        // 判断loading状态 选择是否触发上拉加载
        if (this.isLoading) return
        // 上拉触发页码自增
        this.queryObj.pagenum += 1
        // 自增后重新获取列表
        this.getGoodsList()
      },

      // 下拉加载
      onPullDownRefresh() {
        // 重置数据
        this.queryObj.pagenum = 1
        this.total = 0
        this.isLoading = false
        this.goodsList = []
        // 重新发起数据请求
        this.getGoodsList(() => uni.stopPullDownRefresh())
      },
      
      // 跳转商品详情页面
      gotoDetail(goods) {
        uni.navigateTo({
          url:'/subpkg/goods_detail/goods_detail?good_id=' + goods.goods_id
        })
      } 
    }
  }
</script>

<style lang="scss">

</style>
